layui.define(['layer', 'table', 'toast'], function (exports) {
    "use strict";

    var MOD_NAME = 'aphp',
        layer = layui.layer,
        $ = layui.$,
        toast = layui.toast,
        table = layui.table;

    var aphp = {
        config: {
            shade: [0.02, '#000'],
        },
        // 检测权限
        checkAuth: function (node, ele) {
            let attr = $(ele).data("auth-" + node);
            if (typeof attr === 'undefined' || attr) {
                return true;
            }
            if(node.indexOf('?')>=0) node = node.replace(/([?#])[^'"]*/, '');
            return $(ele).attr('data-auth-' + node.toLowerCase()) === '1';
        },
        // 获取参数
        getParam: function(param, defaultParam) {
            return param !== undefined ? param : defaultParam;
        },
        // 是否是手机端
        isMobile: function() {
            // 根据屏幕分辨率判断
            if (window.screen.width < 600 && window.screen.height < 800) {
                return true;
            }
            // 根据userAgent判断
            var regexMobile = /Android|webOS|iPhone|iPad|iPod|SymbianOS|Windows Phone|BlackBerry|IEMobile|Opera Mini/i;
            return regexMobile.test(navigator.userAgent);
        },
        // 修正URL地址
        fixUrl: function(url) {
            if (url.slice(0, 1) !== "/") {
                var r = new RegExp('^(?:[a-z]+:)?//', 'i');
                if (!r.test(url)) {
                    url = "/" + url;
                }
            }
            return url;
        },
        // 获取选中IDS
        getCheckedIds: function (tableId) {
            let data = table.checkStatus(tableId).data;
            if (data.length === 0) {
                return '';
            }
            let ids = '';
            for (let i = 0; i < data.length; i++) {
                ids += data[i].id + ',';
            }
            return ids.slice(0, -1);
        },
        // 打开窗口
        open: function(title, url, width, height, options, isResize) {
            isResize = isResize === undefined ? true : isResize;
            var area = aphp.config.openArea !== undefined ? aphp.config.openArea : [$(window).width() > width ? width + 'px' : '95%', $(window).height() > height ? height + 'px' : '95%'];
            options = $.extend({
                title: title,
                type: 2,
                area: area,
                content: url + (url.indexOf("?") > -1 ? "&" : "?") + "dialog=1",
                maxmin: true,
                moveOut: true,
                success: function(layero, index) {
                    var that = this;
                    $(layero).data("callback", that.callback);
                    layer.setTop(layero);
                    try {
                        var frame = layer.getChildFrame('body', index);
                        var layerfooter = frame.find(".layer-footer");
                        aphp.layerfooter(layero, index, that);
                        if (layerfooter.size() > 0) {
                            var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
                            if (MutationObserver) {
                                var target = layerfooter[0];
                                var observer = new MutationObserver(function(mutations) {
                                    aphp.layerfooter(layero, index, that);
                                    mutations.forEach(function(mutation) {});
                                });
                                var config = { attributes: true, childList: true, characterData: true, subtree: true }
                                observer.observe(target, config);
                            }
                        }
                    } catch (e) {
                    }
                    if (frame && frame.length > 0) {
                        $.each(frame, function(i, v) {
                            $(v).before('<style>\n' +
                                'html, body {\n' +
                                '    background: #ffffff !important;\n' +
                                '}\n' +
                                '</style>');
                        });
                    }
                    if (aphp.isMobile() || width === undefined || height === undefined) {
                        layer.full(index);
                    }
                    if (isResize) {
                        $(window).on("resize", function() {
                            layer.style(index, { top: 0, height: $(window).height() });
                        })
                    }
                }
            }, options ? options : {});
            return layer.open(options);
        },
        // 关闭窗口并回传数据
        close: function(data) {
            var index = parent.layer.getFrameIndex(window.name);
            var callback = parent.$("#layui-layer" + index).data("callback");
            //再执行关闭
            parent.layer.close(index);
            //再调用回传函数
            if (typeof callback === 'function') {
                callback.call(undefined, data);
            }
        },
        // 窗口底部按钮
        layerfooter: function(layero, index, that) {
            var frame = layer.getChildFrame('html', index);
            var layerfooter = frame.find(".layer-footer");
            //表单按钮
            if (layerfooter.size() > 0) {
                $(".layui-layer-footer", layero).remove();
                var footer = $("<div />").addClass('layui-layer-btn layui-layer-footer');
                footer.html(layerfooter.html());
                footer.insertAfter(layero.find('.layui-layer-content'));
                //绑定事件
                footer.on("click", ".layui-btn", function() {
                    if ($(this).hasClass("disabled") || $(this).parent().hasClass("disabled")) {
                        return;
                    }
                    var index = footer.find('.layui-btn').index(this);
                    $(".layui-btn:eq(" + index + ")", layerfooter).trigger("click");
                });
                var titHeight = layero.find('.layui-layer-title').outerHeight() || 0;
                var btnHeight = layero.find('.layui-layer-btn').outerHeight() || 0;
                //重设iframe高度
                $("iframe", layero).height(layero.height() - titHeight - btnHeight);
            }
        },
        // 跳转处理 refresh: 1刷新页面 2跳转url 0自定义
        jump: function (ret, refresh, success, fail) {
            refresh = refresh || 0;
            success = (refresh === 1)? function () { window.location.reload(); } : (refresh === 2) ? function () { window.location.href = ret.url; } : success;
            fail = fail || function () {};
            if (ret.status === 1) {
                layer.msg(ret.msg, { icon: 1, shade: aphp.config.shade, scrollbar: false, time: 1000, shadeClose: true }, success);
            } else {
                layer.msg(ret.msg, { icon: 2, shade: aphp.config.shade, scrollbar: false, time: 2000, shadeClose: true }, fail);
            }
        },
        // 提示信息
        msg: {
            // 成功消息
            success: function(msg, callback) {
                callback = callback || function() {};
                return layer.msg(msg, { icon: 1, shade: aphp.config.shade, scrollbar: false, time: 2000, shadeClose: true }, callback);
            },
            // 失败消息
            error: function(msg, callback) {
                callback = callback || function() {};
                return layer.msg(msg, { icon: 2, shade: aphp.config.shade, scrollbar: false, time: 3000, shadeClose: true }, callback);
            },
            // 警告消息框
            alert: function(msg, callback) {
                return layer.alert(msg, {end: callback, scrollbar: false});
            },
            // 对话框
            confirm: function(msg, ok, no) {
                return layer.confirm(msg, {icon: 3, title: '操作确认', btn: ['确认', '取消']}, function () {
                    typeof ok === 'function' && ok.call(this);
                }, function (index) {
                    typeof no === 'function' && no.call(this);
                    layer.close(index);
                });
            },
            // 消息提示
            tips: function(msg, time, callback) {
                return layer.msg(msg, {time: (time || 3) * 1000, shade: this.shade, end: callback, shadeClose: true});
            },
            // 加载中提示
            loading: function(msg, callback) {
                return msg ? layer.msg(msg, {
                    icon: 16,
                    scrollbar: false,
                    shade: this.shade,
                    time: 0,
                    end: callback
                }) : layer.load(2, {time: 0, scrollbar: false, shade: this.shade, end: callback});
            },
            // 关闭消息框
            close: function(index) {
                return layer.close(index);
            }
        },
        // 通知信息
        toast: {
            // 成功消息
            success: function(msg, callback) {
                callback = callback || '';
                toast.success({ message: msg, position: 'center'}); // , progressBar: true
                if (callback && typeof callback === 'function') {
                    setTimeout(callback, 2000);
                }
            },
            // 失败消息
            error: function(msg, callback) {
                callback = callback || '';
                toast.error({ message: msg });
                if (callback && typeof callback === 'function') {
                    setTimeout(callback,3000);
                }
            },
            // 消息提示
            info: function(msg) {
                toast.info({ message: msg });
            },
            // 警告消息框
            warning: function(msg) {
                toast.warning({ message: msg });
            }
        },
        // 请求处理
        request: {
            // ajax get
            get: function (url, refresh, success) {
                refresh = refresh || 0;
                success = success || function () {};
                var load = layer.load();
                $.get(url, function (ret) {
                    layer.close(load);
                    aphp.jump(ret, refresh, success);
                },'json');
            },
            // 确认 ajax get
            getConfirm: function (url, confirm, refresh, success) {
                confirm = confirm || '确定进行该操作吗？';
                layer.confirm(confirm, { icon: 3, title: '提示' }, function (index) {
                    layer.close(index);
                    aphp.request.get(url, refresh, success);
                });
            },
            // ajax post
            post: function (url, data, refresh, success, fail) {
                refresh = refresh || 0;
                success = success || function () {};
                fail = fail || function () {};
                var load = layer.load();
                $.post(url, data, function (ret) {
                    layer.close(load);
                    aphp.jump(ret, refresh, success, fail);
                }, 'json');
            },
            // 确认 ajax post
            postConfirm: function (url, data, confirm, refresh, success, fail) {
                confirm = confirm || '确定进行该操作吗？';
                layer.confirm(confirm, { icon: 3, title: '提示' }, function (index) {
                    layer.close(index);
                    aphp.request.post(url, data, refresh, success, fail);
                });
            },
            // ajax post form
            postForm: function (data, refresh, success, fail) {
                aphp.request.post(data.form.action, data.field, refresh, success, fail);
            },
        },
        // 本地缓存
        cache: {
            setStorage: function(key, value) {
                if (value != null && value !== "undefined") {
                    layui.data(key, { key: key, value: value });
                } else {
                    layui.data(key, { key: key, remove: true });
                }
            },
            getStorage: function(key) {
                var array = layui.data(key);
                return array ? array[key] : false;
            }
        },
        getApi: function(url, field) {
            field = 'aphp_' + field || 'abc';
            var abc = aphp.cache.getStorage(field);
            if (!abc) {
                $.getJSON(url, function (res){
                    aphp.cache.setStorage(field, res);
                });
                return aphp.cache.getStorage(field);
            }
            return abc;
        },
        // 初始化
        init: function() {
            // toast初始设置
            toast.settings({
                timeout: 3000,
                position: 'center',
            });
            // layer初始设置
            layer.config({ skin: 'layui-layer-aphp' });
            // 提示信息
            var tips_index = 0;
            $(document).on('mouseenter', '[lay-tips]', function () {
                tips_index = layer.tips($(this).attr('lay-tips'), this, { time: 0 });
            }).on('mouseleave', '[lay-tips]', function(){
                layer.close(tips_index);
            });
            // 修复含有fixed-footer类的body边距
            if ($(".fixed-footer").size() > 0) {
                $(document.body).css("padding-bottom", $(".fixed-footer").outerHeight());
            }
            // 修复不在iframe时layer-footer隐藏的问题
            if ($(".layer-footer").size() > 0 && self === top) {
                $(".layer-footer").show();
            }
            // 对相对地址进行处理
            $.ajaxSetup({
                beforeSend: function(xhr, setting) {
                    setting.url = aphp.fixUrl(setting.url);
                }
            });
            // 放大图片事件绑定
            $(document).on('click', '[data-image]', function() {
                var title = $(this).attr('data-image'),
                    src = $(this).attr('src'),
                    alt = $(this).attr('alt');
                var photos = {
                    "title": title,
                    "id": Math.random(),
                    "data": [{
                        "alt": alt,
                        "pid": Math.random(),
                        "src": src,
                        "thumb": src
                    }]
                };
                layer.photos({ photos: photos, anim: 5});
                return false;
            });
            // 绑定ESC关闭窗口事件
            $(window).keyup(function (e) {
                if (e.keyCode === 27) {
                    if ($(".layui-layer").length > 0) {
                        var index = 0;
                        $(".layui-layer").each(function () {
                            index = Math.max(index, parseInt($(this).attr("times")));
                        });
                        if (index) {
                            layer.close(index);
                        }
                    }
                }
            });
            // 监听打开新增选项卡
            $(document).on('click', '.btn-addtabs,.addtabsit', function (e) {
                let that = this;
                let id = $(that).data("menu-id") || Math.round(Math.random() * (99999-10000) + 10000);
                let url = $(that).data("url") || $(that).attr('href');
                let title = $(that).attr("title") || $(that).data("title") || $(that).data('original-title');
                if (!$(this).attr('data-menu-id')) {
                    $(this).attr('data-menu-id', id);
                }
                if (parent.layui.admin) {
                    parent.layui.admin.addTab(id, title, url);
                } else if(window.top.layui.admin){
                    window.top.layui.admin.addTab(id, title, url);
                }
            });
            // 监听打开弹出层
            $(document).on('click', '[data-open]', function() {
                var url = $(this).data('open'),
                    title = $(this).data('title') || $(this).attr('title') || '弹窗',
                    width = $(this).data('width') || 800,
                    height = $(this).data('height') || 600,
                    fullscreen = $(this).data('full') || false,
                    tableId = $(this).data('table') || 'currentTable',
                    checkbox = $(this).data('checkbox') || false;
                if (fullscreen === true || fullscreen === 'true') {
                    width = '100%';
                    height = '100%';
                }
                if (checkbox !== false) {
                    var ids = aphp.getCheckedIds(tableId);
                    if (ids === '') {
                        layer.msg('请选择ID', {icon: 3, time: 1500});
                        return false;
                    }
                    var field = (typeof checkbox === 'string') ? checkbox : 'id';
                    url += (url.indexOf("?") === -1 ? "?" : "&") + field + '=' + ids;
                }
                aphp.open(title, url, width, height);
            });
            // 复制文本
            $(document).on('click', '.copy', function () {
                var text = $(this).data('copy-text') || $(this).text();
                var title = $(this).attr('title') || '复制';
                var copy_by = $(this).data('copy-by') || '';
                if (copy_by !== '') {
                    text = $(copy_by).text() || $(copy_by).val();
                }
                lay.clipboard.writeText({
                    text: text,
                    done: function () {
                        layer.msg(title + '成功', {icon: 1});
                    },
                    error: function () {
                        layer.msg(title + '失败', {icon: 2});
                    }
                });
            });
        },
    };

    aphp.init();
    exports(MOD_NAME, aphp);
});